from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.dataCheck import DataCheck
from question.models import SoftwareQuestion, QuestionHandle
from software.models import Software, SoftwareVersion
from announcement.models import Announcement
import pdb, os

import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
datacheck = DataCheck()


def questionScreen(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            warZoneId:data.warZoneId,//战区id
            companyId:data.companyId,//单位id
            storehouseId:data.storehouseId,//仓库id
            softwareVesionId:data.id,//软件id

            key:data.key,//关键词
            needState:data.needState,//:0：未处理，1：已处理，2：归档（删除）

            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'questionlist':[{
                'questionId':null,
                'softwareName':null,
                'iconUrl':null,//软件图标
                'storehouseName':null,//仓库名称
                'version':null,//软件版本
                'username':null,//提问人
                'raiseTime':null,//提问时间
                'questionTitle':null,//问题标题
                'questionContent':null,//问题内容
                'dealName':null,//回复人
                'dealTime':null,//回复时间
                'handleContent':null,//问题回复
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if requestParam['key'] != '':
        filterDict['softwareVersion__softwareName__icontains'] = requestParam['key']
        # to do 关键字描述

    if requestParam['questionState'] != '':
        if requestParam['questionState'] == '0':
            filterDict['isActive'] = True
            filterDict['ishandle'] = False

        elif requestParam['questionState'] == '1':
            filterDict['ishandle'] = True
            filterDict['isActive'] = True
        elif requestParam['questionState'] == '2':
            filterDict['isActive'] = False
        else:
            data = {
                "code": 1,
                "msg": "state Error",
                'totalNum': 0,
                'questionlist': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['storehouseId'] != None:
        filterDict['softwareVersion__store__id'] = requestParam['storehouseId']  ##后期改成版本
    if requestParam['warZoneId'] != None:
        filterDict['user__warZone__id'] = requestParam['warZoneId']
        if requestParam['companyId'] != None:
            filterDict['user__company__id'] = requestParam['companyId']
            # pdb.set_trace()
    questionlist = SoftwareQuestion.objects.filter(**filterDict).order_by('-createTime')
    if questionlist.exists():
        questionLists = []
        totalNum = len(questionlist)
        for question in questionlist:
            if requestParam['questionState'] == '0':
                questionlist = {
                    'softwareName': question.softwareVersion.softwareName,
                    'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                        question.softwareVersion.logo.filePath)[1],
                    'questionId': question.id,
                    'questionState': question.questionState,
                    'storehouseName': question.softwareVersion.store.storehouseName,
                    'version': question.softwareVersion.version,
                    'username': question.user.name,
                    'warZoneName': question.user.warZone.name,
                    'companyName': question.user.company.name,
                    'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'questionTitle': question.title,
                    'questionContent': question.questionContent,
                    'handleContent': '',
                    'dealName': '',
                    'dealTime': '',
                }
                questionLists.append(questionlist)
            elif requestParam['questionState'] == '1':
                handle = QuestionHandle.objects.filter(question=question).first()
                questionlist = {
                    'softwareName': question.softwareVersion.softwareName,
                    'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                        question.softwareVersion.logo.filePath)[1],
                    'questionId': question.id,
                    'questionState': question.questionState,
                    'storehouseName': question.softwareVersion.store.storehouseName,
                    'version': question.softwareVersion.version,
                    'username': question.user.name,
                    'warZoneName': question.user.warZone.name,
                    'companyName': question.user.company.name,
                    'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'questionTitle': question.title,
                    'questionContent': question.questionContent,
                    'handleContent': handle.handleContent,
                    'dealName': handle.user.name,
                    'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                questionLists.append(questionlist)
            elif requestParam['questionState'] == '2':
                if question.ishandle == False:
                    questionlist = {
                        'softwareName': question.softwareVersion.softwareName,
                        'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                            question.softwareVersion.logo.filePath)[1],
                        'questionId': question.id,
                        'questionState': question.questionState,
                        'storehouseName': question.softwareVersion.store.storehouseName,
                        'version': question.softwareVersion.version,
                        'username': question.user.name,
                        'warZoneName': question.user.warZone.name,
                        'companyName': question.user.company.name,
                        'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'questionTitle': question.title,
                        'questionContent': question.questionContent,
                        'handleContent': '',
                        'dealName': '',
                        'dealTime': '',
                    }
                    questionLists.append(questionlist)
                elif question.ishandle == True:
                    handle = QuestionHandle.objects.filter(question=question).first()
                    questionlist = {
                        'softwareName': question.softwareVersion.softwareName,
                        'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                            question.softwareVersion.logo.filePath)[1],
                        'questionId': question.id,
                        'questionState': question.questionState,
                        'storehouseName': question.softwareVersion.store.storehouseName,
                        'version': question.softwareVersion.version,
                        'username': question.user.name,
                        'warZoneName': question.user.warZone.name,
                        'companyName': question.user.company.name,
                        'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'questionTitle': question.title,
                        'questionContent': question.questionContent,
                        'handleContent': handle.handleContent,
                        'dealName': handle.user.name,
                        'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    questionLists.append(questionlist)

        result = questionLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                        requestParam[
                                                                                                            'page'] *
                                                                                                        requestParam[
                                                                                                            'maxItem'])]

    else:
        data = {
            "code": 0,
            "msg": "success",
            'totalNum': 0,
            'questionlist': []
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'questionlist': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def getQuestionList(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            softwareVesionId:data.id,//软件id
            needState:data.needState,//:0：未处理，1：已处理，2：归档（删除）

            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'questionlist':[{
                'questionId':null,
                'softwareName':null,
                'iconUrl':null,//软件图标
                'storehouseName':null,//仓库名称
                'version':null,//软件版本
                'username':null,//提问人
                'raiseTime':null,//提问时间
                'questionTitle':null,//问题标题
                'questionContent':null,//问题内容
                'dealName':null,//回复人
                'dealTime':null,//回复时间
                'handleContent':null,//问题回复
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if requestParam['questionState'] != '':
        if requestParam['questionState'] == '0':
            filterDict['isActive'] = True
            filterDict['ishandle'] = False

        elif requestParam['questionState'] == '1':
            filterDict['ishandle'] = True
            filterDict['isActive'] = True
        elif requestParam['questionState'] == '2':
            filterDict['isActive'] = False
        else:
            data = {
                "code": 1,
                "msg": "state Error",
                'totalNum': 0,
                'questionlist': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['softwareVersionId'] != None:
        filterDict['softwareVersion__id'] = requestParam['softwareVersionId']  ##后期改成版本
    # pdb.set_trace()
    questionlist = SoftwareQuestion.objects.filter(**filterDict).order_by('-createTime')
    if questionlist.exists():
        questionLists = []
        totalNum = len(questionlist)
        for question in questionlist:
            if requestParam['questionState'] == '0':
                questionlist = {
                    'softwareName': question.softwareVersion.softwareName,
                    'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                        question.softwareVersion.logo.filePath)[1],
                    'questionId': question.id,
                    'storehouseName': question.softwareVersion.store.storehouseName,
                    'version': question.softwareVersion.version,
                    'username': question.user.name,
                    'warZoneName': question.user.warZone.name,
                    'companyName': question.user.company.name,
                    'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'questionTitle': question.title,
                    'questionState': question.questionState,
                    'questionContent': question.questionContent,
                    'handleContent': '',
                    'dealName': '',
                    'dealTime': '',
                }
                questionLists.append(questionlist)
            elif requestParam['questionState'] == '1':
                handle = QuestionHandle.objects.filter(question=question).first()
                questionlist = {
                    'softwareName': question.softwareVersion.softwareName,
                    'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                        question.softwareVersion.logo.filePath)[1],
                    'questionId': question.id,
                    'storehouseName': question.softwareVersion.store.storehouseName,
                    'version': question.softwareVersion.version,
                    'username': question.user.name,
                    'warZoneName': question.user.warZone.name,
                    'companyName': question.user.company.name,
                    'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'questionTitle': question.title,
                    'questionContent': question.questionContent,
                    'questionState': question.questionState,
                    'handleContent': handle.handleContent,
                    'dealName': handle.user.name,
                    'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                questionLists.append(questionlist)
            elif requestParam['questionState'] == '2':
                if question.ishandle == False:
                    questionlist = {
                        'softwareName': question.softwareVersion.softwareName,
                        'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                            question.softwareVersion.logo.filePath)[1],
                        'questionId': question.id,
                        'storehouseName': question.softwareVersion.store.storehouseName,
                        'version': question.softwareVersion.version,
                        'questionState': question.questionState,
                        'username': question.user.name,
                        'warZoneName': question.user.warZone.name,
                        'companyName': question.user.company.name,
                        'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'questionTitle': question.title,
                        'questionContent': question.questionContent,
                        'handleContent': '',
                        'dealName': '',
                        'dealTime': '',
                    }
                    questionLists.append(questionlist)
                elif question.ishandle == True:
                    handle = QuestionHandle.objects.filter(question=question).first()
                    questionlist = {
                        'softwareName': question.softwareVersion.softwareName,
                        'iconUrl': download(question.softwareVersion.logo.fileName, 'logo',
                                            question.softwareVersion.logo.filePath)[1],
                        'questionId': question.id,
                        'questionState': question.questionState,
                        'storehouseName': question.softwareVersion.store.storehouseName,
                        'version': question.softwareVersion.version,
                        'username': question.user.name,
                        'warZoneName': question.user.warZone.name,
                        'companyName': question.user.company.name,
                        'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'questionTitle': question.title,
                        'questionContent': question.questionContent,
                        'handleContent': handle.handleContent,
                        'dealName': handle.user.name,
                        'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    questionLists.append(questionlist)

        result = questionLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                        requestParam[
                                                                                                            'page'] *
                                                                                                        requestParam[
                                                                                                            'maxItem'])]

    else:
        data = {
            "code": 0,
            "msg": "success",
            'totalNum': 0,
            'questionlist': []
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'questionlist': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def questionAnnounce(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            noticeId:data.noticeId,//通知Id

            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'questionlist':[{
                'questionId':null,
                'softwareName':null,
                'iconUrl':null,//软件图标
                'storehouseName':null,//仓库名称
                'version':null,//软件版本
                'username':null,//提问人
                'raiseTime':null,//提问时间
                'questionTitle':null,//问题标题
                'questionContent':null,//问题内容
                'dealName':null,//回复人
                'dealTime':null,//回复时间
                'handleContent':null,//问题回复
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    user = datacheck.getUser(requestParam['token'])

    anno = Announcement.objects.get(pk=requestParam['noticeId'])
    questionlist = SoftwareQuestion.objects.filter(pk=anno.IdNum)
    # totalNum = len(questionlist)
    if anno.content == '1':
        questionLists = []
        for question in questionlist:
            questionlist = {
                'softwareName': question.softwareVersion.softwareName,
                'iconUrl':
                    download(question.softwareVersion.logo.fileName, 'logo', question.softwareVersion.logo.filePath)[1],
                'questionId': question.id,
                'storehouseName': question.softwareVersion.store.storehouseName,
                'version': question.softwareVersion.version,
                'username': question.user.name,
                'questionState': question.questionState,
                'warZoneName': question.user.warZone.name,
                'companyName': question.user.company.name,
                'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                'questionTitle': question.title,
                'questionContent': question.questionContent,
                'handleContent': '',
                'dealName': '',
                'dealTime': '',
            }
            questionLists.append(questionlist)
    elif anno.content == '2':
        questionLists = []
        for question in questionlist:
            handle = QuestionHandle.objects.filter(question=question).first()
            questionlist = {
                'softwareName': question.softwareVersion.softwareName,
                'iconUrl':
                    download(question.softwareVersion.logo.fileName, 'logo', question.softwareVersion.logo.filePath)[1],
                'questionId': question.id,
                'storehouseName': question.softwareVersion.store.storehouseName,
                'version': question.softwareVersion.version,
                'username': question.user.name,
                'questionState': question.questionState,
                'warZoneName': question.user.warZone.name,
                'companyName': question.user.company.name,
                'raiseTime': question.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                'questionTitle': question.title,
                'questionContent': question.questionContent,
                'handleContent': handle.handleContent,
                'dealName': handle.user.name,
                'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
            }
            questionLists.append(questionlist)

    # result = questionLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
    #                                                                                                 requestParam[
    #                                                                                                     'page'] *
    #                                                                                                 requestParam[
    #                                                                                                     'maxItem'])] 

    data = {
        "code": 0,
        "msg": "success",
        # "totalNum": totalNum,        
        'questionlist': questionLists
    }
    logger_request.info(data)
    return JsonResponse(data)
